package whu.o2o.connection;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import whu.o2o.View.LoadDialog;
import whu.o2o.util.ConstantData;



import android.app.Activity;
import android.os.Handler;
import android.os.Message;

public class CommonHttpConnect implements Runnable {
	private Activity mActivity;
	private Params mParams;

	public CommonHttpConnect(Params params) {
		mParams = params;
		mActivity = mParams.getActivity();
	}

	public void run() {
		String result = httpRequest();
		Handler handler = mParams.getHandler();
		if (handler != null) {
			Message msg = handler.obtainMessage();
			msg.what = mParams.getMsgCode();
			msg.obj = result;
			handler.sendMessage(msg);
		} else if (mParams.isShowLoad()) {
			closeLoadDailog();
		}
	}

	private String httpRequest() {
		HttpClient httpClient = null;
		String result = null;
		try {
			httpClient = new DefaultHttpClient();

			if (ConstantData.Data.GET_HTTP.equals(mParams.getRequestType())) {
				HttpGet httpGet = new HttpGet(mParams.getUrl());
				HttpConnectionParams.setConnectionTimeout(httpGet.getParams(), ConstantData.Data.GET_CONNECTION_TIMEOUT);
				HttpConnectionParams.setSoTimeout(httpGet.getParams(), ConstantData.Data.GET_SO_TIMEOUT);
				HttpConnectionParams.setTcpNoDelay(httpGet.getParams(), true);
				result = httpClient.execute(httpGet, new BasicResponseHandler());

			} else if (ConstantData.Data.POST_HTTP.equals(mParams.getRequestType())) {
				HttpPost httpPost = new HttpPost(mParams.getUrl());
				HttpConnectionParams.setConnectionTimeout(httpPost.getParams(), ConstantData.Data.POST_CONNECTION_TIMEOUT);
				HttpConnectionParams.setSoTimeout(httpPost.getParams(), ConstantData.Data.POST_SO_TIMEOUT);
				httpPost.setEntity(new UrlEncodedFormEntity(mParams.getList(), HTTP.UTF_8));
				HttpResponse httpResponse = httpClient.execute(httpPost);
				if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					result = EntityUtils.toString(httpResponse.getEntity());
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (httpClient != null) {
				httpClient.getConnectionManager().shutdown();
			}
		}
		return result;
	}

	private void closeLoadDailog() {
		if (mActivity != null) {
			mActivity.runOnUiThread(new Runnable() {
				public void run() {
					if (!mActivity.isFinishing()) {
						LoadDialog.closeDialog();
					}
				}
			});
		}

	}
}